import React, { useState, useEffect } from 'react'
import { HashRouter, Route, Routes } from 'react-router-dom'
import Redirect from '@/components/Redirect'
import NoPermission from '@/views/sandbox/nopermission/Nopermission'
import Login from '@/views/login/Login'
import NewsSandBox from '@/views/sandbox/NewsSandBox'

import Home from '@/views/sandbox/home/Home'
import UserList from '@/views/sandbox/user-manage/UserList'

import RoleList from '@/views/sandbox/right-manage/RoleList'
import RightList from '@/views/sandbox/right-manage/RightList'

import NewsAdd from '@/views/sandbox/news-manage/newsAdd/NewsAdd'
import NewsDraft from '@/views/sandbox/news-manage/NewsDraft'
import NewsCategory from '@/views/sandbox/news-manage/NewsCategory'
import NewsPreview from '@/views/sandbox/news-manage/newsPreview/NewsPreview'
import NewsUpdate from '@/views/sandbox/news-manage/newsUpdate/NewsUpdate'

import Audit from '@/views/sandbox/audit-manage/Audit'
import AuditList from '@/views/sandbox/audit-manage/AuditList'

import Unpublished from '@/views/sandbox/publish-manage/Unpublished'
import Published from '@/views/sandbox/publish-manage/Published'
import Sunset from '@/views/sandbox/publish-manage/Sunset'

import News from '@/views/news/News'
import Detail from '@/views/news/Detail'
import {
  getRightListApi
} from '@/api/right'
import {
  getChildrenListApi
} from '@/api/children'

export default function indexRouter() {
  // 设置状态，可以访问的路由
  const [backRouteList, setbackRouteList] = useState([])
  // 从本地获取用户
  const { role: { rights }} = JSON.parse(localStorage.getItem('token'))

  // 发送请求获取可以访问的路由
  useEffect(() => {
    Promise.all([
      getRightListApi(),
      getChildrenListApi()
    ]).then((res) => {
      setbackRouteList([...res[0], ...res[1]])
    })
  }, [])

  const LocalRouterMap = {
    '/home': <Home/>,
    '/user-manage/list': <UserList/>,
    '/right-manage/role/list': <RoleList/>,
    '/right-manage/right/list': <RightList/>,
    '/news-manage/add': <NewsAdd/>,
    '/news-manage/draft': <NewsDraft/>,
    '/news-manage/category': <NewsCategory/>,
    '/news-manage/preview/:id': <NewsPreview/>,
    '/news-manage/update/:id': <NewsUpdate/>,
    '/audit-manage/audit': <Audit/>,
    '/audit-manage/list': <AuditList/>,
    '/publish-manage/unpublished': <Unpublished/>,
    '/publish-manage/published': <Published/>,
    '/publish-manage/sunset': <Sunset/>
  }

  // 判断改路由是否开启
  const checkRoute = (item) => {
    return LocalRouterMap[item.key] && (item.pagepermisson || item.routepermisson)
  }

  // 判断用户是否有访问路由的权限
  const checkUser = (item) => {
    return rights?.includes(item.key)
  }

  return (
    <HashRouter>
      <Routes>
        <Route element={<Login />} path="/login" />
        <Route element={<News />} path="/news" />
        <Route element={<Detail />} path="/detail/:id" />
        <Route element={
          <AuthComponent>
            <NewsSandBox />
          </AuthComponent>} path="/"
        >
          {/* <Route element={<Home />} path="home" />
          <Route element={<UserList />} path="user-manage/list" />
          <Route element={<RoleList />} path="right-manage/role/list" />
          <Route element={<RightList />} path="right-manage/right/list" /> */}
          {
            backRouteList.map(item =>
            {
              // 判断是否有权限
              if (checkRoute(item) && checkUser(item)) {
                return (
                  <Route element={LocalRouterMap[item.key]} key={item.key} path={item.key.substring(1)} />
                )
              } else {
                return null
              }
            }
            )
          }
          <Route element={<Redirect to="home" />} path="" />
          {/* 避免一刷新出现NoPermission页面 */}
          {
            backRouteList.length > 0 && <Route element={<NoPermission />} path="*" />
          }
        </Route>
      </Routes>
    </HashRouter>
  )
}

function AuthComponent({ children }) {
  const isLogin = localStorage.getItem('token')
  return isLogin ? children : <Redirect to="/login" />
}